#include<stdio.h>
#include<stdlib.h>
#include<math.h>

int Duplicate(int num[]);
void DataSort(int *num);
int Maxium(int *num);
int Minium(int *num);

int main()
{	 	   	
    int num[4];
    int number, flag, max, min;
    int i;

    printf("请输入数字：");
    scanf("%d", &number);

    for (i = 0; i < 4; i++)
        num[i] = (int)(number / pow(10.0, (double)i)) % 10; //将四位数每一个分别取出

    flag = Duplicate(num);
    if (flag == 1)
    {	 	   	
        printf("各个位置数字完全相同，不是卡布列克数\n");
        return 0;
    }
    DataSort(num);
    max = Maxium(num);
    min = Minium(num);
    number = max - min; //求出最大数减去最小数所得的数
    printf("%d-%d=%d\n", max, min, number); //输出每次运算步骤
    while (number != 6174)
    {	 	   	
        for (i = 0; i < 4; i++)
            num[i] = (int)(number / pow(10.0, (double)i)) % 10;
        DataSort(num);
        max = Maxium(num);
        min = Minium(num);
        number = max - min; //求出最大数减去最小数所得的数
        printf("%d-%d=%d\n", max, min, number); //输出每次运算步骤
    }
    return 0;
}	 	   	

int Duplicate(int num[])
{	 	   	

    int flag = 1, i, j;
    for (i = 0; i < 3; i++) //判定是否有不重复的数字
    {	 	   	
        for (j = i + 1; j < 4; j++)
            if (num[i] != num[j])
            {	 	   	
                flag = 0;
                break;
            }
        if (flag == 0)
            break;
    }
    return flag;

}	 	   	
void DataSort(int num[])//将四个数从大到小排序
{	 	   	
    int i, j, temp;
    for (i = 0; i < 4; i++)
        for (j = 0; j < 3 - i; j++)
            if (num[j] < num[j + 1]) //也可用其它排序算法
            {	 	   	
                temp = num[j];
                num[j] = num[j + 1];
                num[j + 1] = temp;
            }
}	 	   	
int Maxium(int num[])//求出四个数组成的最大数
{	 	   	
    int max = 0, i;
    for (i = 0; i < 4; i++)
        max = max + (int)(num[i] * pow(10.0, 3 - i));
    return max;
}	 	   	

int Minium(int num[])//求出四个数组成的最小数
{	 	   	
    int min = 0, i;
    for (i = 0; i < 4; i++)
        min = min + (int)(num[i] * pow(10.0, i));
    return min;
}	 	   	